<template>
    <div class="content">
      <div class="content-head">
        <el-form :inline="true" size="mini" label-position="left">
          <el-form-item label="班组" label-width="50px" class="form-item">
            <el-select v-model="formData.classesTeam" filterable size="small" placeholder="下拉选择班组">
              <el-option v-for="v in formData.classesTeamList" :label="v.teamName" :value="v.id" :key="v.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="月份" label-width="50px" class="form-item">
            <el-date-picker v-model="formData.month" :editable="false" type="month" value-format="yyyy-MM" size="small" placeholder="选择月份" class="el-date-picker"></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" icon="el-icon-refresh-left" @click="resetBtn">重置</el-button>
            <el-button type="success" size="small" icon="el-icon-search" @click="searchBtn">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="content-table">
        <div class="table-btn" style="margin: 10px;">
          <el-button type="primary" size="small" icon="el-icon-plus" @click="addSchedulingBtn">添加排班</el-button>
        </div>
        <div class="table-main">
          <el-table :data="tableData" v-loading="tableLoading" style="width: 100%;" :max-height="tableMaxHeight" class="content-table-item">
            <el-table-column prop="" type="index" label="序号" width="100"></el-table-column>
            <el-table-column prop="month" label="月份" width=""></el-table-column>         
            <el-table-column prop="teamName" label="班组" width=""></el-table-column>
            <el-table-column prop="shiftName" label="班次" width=""></el-table-column>
            <el-table-column prop="remark" label="备注" width=""></el-table-column>
            <el-table-column prop="createdDate" label="创建时间" width=""></el-table-column>
            <el-table-column prop="" label="操作" align="center" width="">
              <template slot-scope="{ row, $index }">
                <el-button type="text" size="mini" @click="editBtn(row, $index)" style="margin-right:10px;">编辑</el-button>
                <el-popconfirm title="确定删除吗？" @confirm="deleteBtn(row, $index)">
                  <el-button slot="reference" type="text" size="mini">删除</el-button>
                </el-popconfirm>
              </template>
            </el-table-column> 
          </el-table>
        </div>
      </div>
      <div class="content-footer">
        <el-pagination @size-change="handleSizeChange"  @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10,20,30,50,100,200]" :page-size="pageSize" background layout="prev, pager, next,total, sizes, jumper" :total="total"></el-pagination>
      </div>
      <!-- dialog -->
      <el-dialog :title="dialogStatus === 0 ? '添加排班' : '编辑排班'" :visible.sync="dialogFormVisible" width="30%" @close="dialogFormCancel">
        <el-form :model="dialogFormData" size="mini" label-width="100px">
          <el-form-item label="月份">
            <el-date-picker v-model="dialogFormData.month" :editable="false" type="month" value-format="yyyy-MM" size="small" placeholder="选择月份" class="el-date-picker" style="width: 60%;"></el-date-picker>
          </el-form-item>
          <el-form-item label="班组">
            <el-select v-model="dialogFormData.classesTeamId" filterable size="small" placeholder="下拉选择班组">
              <el-option v-for="v in formData.classesTeamList" :label="v.teamName" :value="v.id" :key="v.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="班次">
            <el-select v-model="dialogFormData.classesId" filterable size="small" placeholder="下拉选择班次">
              <el-option v-for="v in formData.classesList" :label="v.shiftType" :value="v.classesId" :key="v.classesId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="dialogFormData.remark" type="textarea" autocomplete="off" placeholder="输入备注内容" style="width:70%;"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" size="mini" @click="dialogFormConfirm">确定</el-button>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { reqTeamsList, reqClassesList, reqSchedulingList, reqSchedulingEdit, reqSchedulingSave, reqSchedulingDel } from "@/api/classes.js";
  import { portrait, autoOrientation, fullscreen } from "@/utils/rotatingScreen.js";
  export default {
    name:"classAdjust",
    data() {
      return {
        formData:{
          classesTeam:"",
          month:"",
          classesTeamList:[],
          classesList:[]
        },
        dialogFormData:{
          id:"",
          month:"",
          classesTeam:"",
          classesTeamId:"",
          classes:"",
          classesId:"",
          remark:""
        },
        dialogFormVisible:false,
        dialogStatus:0,  //0 - 新增 1 - 编辑
        tableData:[],
        currentPage:1,
        pageSize:10,
        total:0,
        tableLoading:false,
        tableMaxHeight:450
      }
    },
    mounted(){
      document.title = "班次配置";
      this.calculateTableMaxHeight();
      window.addEventListener('resize',this.calculateTableMaxHeight);
      this.getSchedulingList();
      this.getClassTeamList();
      this.getClassesList();
    },
    beforeDestroy(){
      window.removeEventListener('resize',this.calculateTableMaxHeight);
    },
    methods:{
      //获取班组列表信息
      getClassTeamList(){
        reqTeamsList().then(response => {
          if(response.data.code === 200 && response.data.data.content){
            const list = response.data.data.content;
            const tmp = list.map(v => {
              return {
                id:v.id,
                teamCode:v.teamCode,
                teamName:v.teamName,
                teamType:v.teamType
              }
            })
            this.formData.classesTeamList = tmp;
          }
          console.log('获取班组列表信息',response);
        },error => {
          this.$notify.error({title: '提示',message: '班组列表请求失败'});
          console.log('获取班组列表信息',error);
        })
      },
      getClassesList(){
        reqClassesList().then(response => {
          if(response.data.code === 200 && response.data.data){
            const list = response.data.data;
            const tmp = list.map(v => {
              return {
                classesId:v.id,
                shiftType:v.shiftType
              }
            })
            this.formData.classesList = tmp;
          }
          console.log('获取班次列表信息',response);
        },error => {
          this.$notify.error({title: '提示',message: '班次列表请求失败'});
          console.log('获取班次列表信息',error);
        })
      },
      getSchedulingList(){
        const tmName = this.formData.classesTeamList.find(v => v.id === this.formData.classesTeam)?.teamName || '';
        const parameter = {page:this.currentPage,size:this.pageSize,month:this.formData.month,teamName:tmName};
        this.tableLoading = true;
        reqSchedulingList(parameter).then(response => {
          if(response.data.code === 200 && response.data.data){
            this.tableData = response.data.data.content;
            this.total = response.data.data.totalElements;
          }
          this.tableLoading = false;
          console.log('获取排班列表信息',response);
        },error => {
          this.tableLoading = false;
          console.log('获取排班列表信息',error);
        })
      },
      updateScheduling(){
        return new Promise (async (resolve,reject) => {
          const { id, month,classesTeam,classesTeamId,classes, classesId, remark } = this.dialogFormData;
          const parameter = {
            id:id,
            month:month,
            teamId:classesTeamId,
            teamName:this.formData.classesTeamList.find(v => v.id === classesTeamId)?.teamName || '',
            shiftId:classesId,
            shiftName:this.formData.classesList.find(v => v.classesId === classesId).shiftType,
            remark:remark
          }
          let type = false;
          const tmp = this.tableData.find(v => v.id === parameter.id);
          if(tmp.month === parameter.month && tmp.teamName === parameter.teamName){
            type = true;
          }
          const isRepeat = await this.checkSchedulingIsRepeat(parameter.month,parameter.teamName,type);
          if(isRepeat){
            this.$confirm("已存在相同的排班信息，请核对后再修改!", '提示', { type: 'warning'});
            resolve("检测到重复");
            return;
          }
          reqSchedulingEdit(parameter).then(response => {
            console.log('更新排班信息',response);
            resolve();
          },error => {
            console.log("更新排班信息",error)
            reject();
          })
        })
      },
      createScheduling(){
        return new Promise(async (resolve,reject) => {
          const { month,classesTeamId, classesId, remark } = this.dialogFormData;
          const parameter = {
            month:month,
            teamId:classesTeamId,
            teamName:null,
            shiftId:classesId,
            shiftName:null,
            remark:remark
          }
          parameter.teamName = this.formData.classesTeamList.find(v => v.id === classesTeamId).teamName;
          parameter.shiftName = this.formData.classesList.find(v => v.classesId === classesId).shiftType;
          const isRepeat = await this.checkSchedulingIsRepeat(parameter.month,parameter.teamName);
          if(isRepeat){
            this.$confirm("已存在相同的排班信息，请核对后再添加!", '提示', { type: 'warning'});
            resolve("检测到重复");
            return;
          }
          reqSchedulingSave(parameter).then(response => {
            console.log('保存排班信息',response);
            resolve();
          },error => {
            console.log("保存排班信息",error);
            reject();
          })
        })
      },
      async dialogFormConfirm(){
        const status = this.dialogStatus;
        if(status === 0){
          await this.createScheduling();
        } else if (status === 1) {
          await this.updateScheduling();
        }
        this.dialogFormCancel();
        this.getSchedulingList();
      },
      dialogFormCancel(){
        this.dialogFormVisible = false;
        this.dialogFormData.id = "";
        this.dialogFormData.month = "";
        this.dialogFormData.classesTeam = "";
        this.dialogFormData.classesTeamId = "";
        this.dialogFormData.classes = "";
        this.dialogFormData.classesId = "";
        this.dialogFormData.remark = "";
      },
      addSchedulingBtn(){
        this.dialogFormVisible = true;
        this.dialogStatus = 0;
      },
      editBtn(row,index){
        const { id,month,teamName,teamId,shiftName,shiftId,remark } = row;
        this.dialogFormData.id = id;
        this.dialogFormData.month = month;
        this.dialogFormData.classesTeam = teamName;
        this.dialogFormData.classesTeamId = teamId;
        this.dialogFormData.classes = shiftName;
        this.dialogFormData.classesId = shiftId;
        this.dialogFormData.remark = remark;
        this.dialogFormVisible = true;
        this.dialogStatus = 1;
      },
      deleteBtn(row,index){
        const id = row.id;
        reqSchedulingDel(id).then(response => {
          if(response.data.code === 200){
            this.$message({type:"success",message:"删除成功"});
            this.getSchedulingList();
          }
          console.log('排班删除api',response);
        },error => {
          console.log('排班删除api',error);
        })
      },
      searchBtn(){
        if(!(this.formData.classesTeam || this.formData.month)){
          this.$message({type:"warning",message:"请选择合适筛选条件"});
          return;
        }
        this.getSchedulingList();
      },
      resetBtn(){
        this.formData.classesTeam = "";
        this.formData.month = "";
        this.getSchedulingList();
      },
      //检测是否添加或者编辑成重复的排班
      checkSchedulingIsRepeat(month,teamName,type = false){
        console.log('====',month,teamName,type);
        return new Promise((resolve,reject) => {
          const parameter = {page:1,size:10,month,teamName};
          reqSchedulingList(parameter).then(response => {
            if(response.data.code === 200 && response.data.data){
              const list = response.data.data.content;
              const len = list.filter(v => v.teamName === teamName && v.month === month).length;
              if(len === 0 || type){
                resolve(false);
              } else {
                resolve(true);
              }
            }
            resolve("请求排班列表失败");
            console.log('获取排班列表信息',response);
          },error => {
            console.log('获取排班列表信息',error);
            reject("请求排班列表失败");
          })
        })
      },
      //分页器
      handleCurrentChange(curPage){
        this.currentPage = curPage;
        this.getSchedulingList();
      },
      handleSizeChange(pageSize){
        this.pageSize = pageSize;
        this.getSchedulingList();
      },
      calculateTableMaxHeight(){
        const dom = document.querySelector(".table-main");
        this.$nextTick(() => {
          this.tableMaxHeight = dom.offsetHeight - 10;
        })
      },
      //格式化时间
      formatDate(val,type){
        let date = new Date(val);
        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();
        let h = date.getHours();
        let m = date.getMinutes();
        let s = date.getSeconds();
        if(type === 0){
            return year + "-" + this.addZero(month) + "-" + this.addZero(day) + " " + this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
        } else if (type === 1){
            return year + "-" + this.addZero(month) + "-" + this.addZero(day);
        } else if (type === 2){
            return this.addZero(h) + ":" + this.addZero(m) + ":" + this.addZero(s);
        } else if (type === 3){
            return year + "-" + this.addZero(month) + "-" + this.addZero(day) + " 00:00:00";
        } else if (type === 4){
          return year + "年" + this.addZero(month) + "月" + this.addZero(day) + "日";
        }
      },
      addZero(val){
        return val > 9 ? val : "0" + val;
      }
    }
  }
  </script>
  
  <style lang='scss' scoped>
  .content{
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    padding: 1% 2%;
    box-sizing: border-box;
  
    .content-head{
      flex: 0.5;
      .form-item{
        margin-right: 2vw;
      }
    }
    .content-table{
      flex: 9;
      margin: 10px 0;
      .table-date{
        width: 100%;
        height: 2%;
        min-height: 15px;
        margin-bottom: 0.5%;
        display: flex;
        justify-content: right;
      }
      .table-main{
        width: 100%;
        height: 98%;
      }
    }
    .content-footer{
      flex: 0.5;
      display: flex;
      justify-content: flex-end;
    }
  }
  ::v-deep .el-table__header th {
    //padding: 0; /* 调整上下内边距 */
  }
  ::v-deep .el-table__row {
    //margin-bottom: 15px; /* 调整这个值来改变行间距 */
  }
  ::v-deep .el-table .el-table__cell{
    //padding: 0;
  }
  ::v-deep .el-input--mini .el-input__inner {
    //height: 22px;
  }
  </style>